package game.clicker;

import game.GameModel;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import application.ArenaManager;

public class Clicker extends GameModel {

	private Container content = getContentPane();

	public Clicker() {
		super();
	}
	
	@Override
	public void startGame() {
		createPanel();
		ArenaManager.getInstance().startGame(this);
	}

	private void createPanel() {
		content.setBackground(Color.white);
		content.setLayout(new FlowLayout());
		content.add(createButtons());
	}
	
	private JPanel createButtons() {
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBackground(Color.white);

		List<JButton> buttons = new ArrayList<JButton>();
		buttons.add(new JButton("1: Hit me to win ;-)!"));
		buttons.add(new JButton("2: No, click me to win!!"));
		buttons.add(new JButton("3: Eh, no... click ME to win!!!"));

		int random = new Random().nextInt(buttons.size());
		int i = 0;

		for (JButton button : buttons) {
			if (i == random) {
				button.addActionListener(new WinnerListener());
			}
			buttonPanel.add(button);
			i++;
		}

		return buttonPanel;
	}

	private class WinnerListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			JButton button = (JButton) e.getSource();
			JFrame frame = findParentFrame();

			JPanel winnerPanel = new JPanel(new FlowLayout());
			winnerPanel.setBackground(Color.white);
			JLabel winnerDesc = new JLabel("Congratulations " + getCurrentPlayer().getName() + ", you won the game!");
			JLabel winnerButton = new JLabel("Winner button was: " + button.getText());
			JPanel buttonPanel = new JPanel(new GridLayout(0, 1));
			buttonPanel.setBackground(Color.white);
			buttonPanel.add(winnerDesc);
			buttonPanel.add(winnerButton);
			winnerPanel.add(buttonPanel);

			JDialog dialog = new JDialog(frame, "Winner = " + getCurrentPlayer().getName(), true);
			dialog.getContentPane().add(winnerPanel);
			dialog.pack();
			dialog.setVisible(true);
			
			alternatePlayer();
		}

		private JFrame findParentFrame() {
			for (Component component : getComponents()) {
				if (component instanceof JFrame) {
					return (JFrame) component;
				}
			}

			return null;
		}
	}

}
